package com.cnswhy.cloud.server.app.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cnswhy.cloud.server.core.vo.RespVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class PageAspect {
    @Pointcut("execution(public * com.cnswhy..*.*Controller.*(..))")
    public void excudeService() {
    }
    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long time1=System.currentTimeMillis();
        Object result = pjp.proceed();
        long time2=System.currentTimeMillis();
        log.debug("获取JSON数据 耗时："+(time2-time1)+"ms");
        long start=System.currentTimeMillis();
        this.parsePageAspent(result);
        long end=System.currentTimeMillis();
        log.debug("解析注入JSON数据  耗时"+(end-start)+"ms");
        return result;
    }
    private void parsePageAspent(Object result) {
        if (result instanceof RespVo) {
            if (((RespVo) result).getResult() instanceof IPage || ((RespVo) result).getResult() instanceof JSONObject ) {
                log.debug("parsePageAspent");
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(((RespVo) result).getResult()));
                log.debug(JSON.toJSONString(jsonObject));
                if (StringUtils.isNotBlank(jsonObject.getString("current"))) {
                    jsonObject.put("currentPage", jsonObject.getIntValue("current"));
                    jsonObject.put("pageSize", jsonObject.getIntValue("size"));
                    jsonObject.put("total", jsonObject.getIntValue("total"));
                    jsonObject.put("currentCount", jsonObject.getIntValue("pages"));
                    jsonObject.put("data", jsonObject.get("records"));
                    jsonObject.remove("records");
                    jsonObject.remove("pages");
                    jsonObject.remove("total");
                    jsonObject.remove("size");
                    jsonObject.remove("current");
                    ((RespVo) result).setResult(jsonObject);
                }
            }
        }
    }
}
